//
//  TestViewController.m
//  test
//
//  Created by 朱圳 on 2018/3/1.
//  Copyright © 2018年 朱圳. All rights reserved.
//

#import "TestViewController.h"
#import "XXAnswerCell.h"
#import "XXTextCell.h"
#import "XXQuestionTitleCell.h"
#import "QuestionsModel.h"
#import "CommentHisVC.h"
#import "NSDate+Extension.h"

@interface TestViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
//页码
@property (nonatomic, assign)NSInteger page;
//底部滚动视图
@property (nonatomic,strong)UIScrollView *contentScrollView;
////tableView
@property (nonatomic,strong)UITableView *tableView;
//上一题
@property (nonatomic,strong)UIButton *topButton;
//下一题
@property (nonatomic,strong)UIButton *nextButton;
//提交按钮
@property (nonatomic,strong)UIButton *submitButton;
@property(nonatomic,strong)UIView *noDataView;
//问题
@property (nonatomic,strong)NSMutableArray *questionArray;
@property (nonatomic,strong)NSMutableArray *didArray;
@property (nonatomic,strong)NSArray *answerArray;
@property (nonatomic,strong)NSString *types;
@property (nonatomic,strong)NSString *questionID;
@property (nonatomic,strong)NSString *advise;
@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HWColor(239, 239, 244);
    self.page = 0;
    [self requestComent];
    self.answerArray = @[@{@"id":@"1",@"xxnr":@"卓越"},@{@"id":@"2",@"xxnr":@"非常满意"},@{@"id":@"3",@"xxnr":@"满意"},@{@"id":@"4",@"xxnr":@"一般"},@{@"id":@"5",@"xxnr":@"差评"}];
    self.advise = @"";
    self.questionID = @"";
    self.types = @"";
}

-(void)requestComent{
    
    NSString *dateString = [[NSDate date] stringWithFormat:@"yyyy-M-d"];
    NSArray *date = [dateString componentsSeparatedByString:@"-"];
    NSString *year = date[0];
    NSString *month = date[1];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{
                           @"sid" : Sid,
                           @"spass" : Spassword,
                           @"year" : year,
                           @"mounth" :month,
                           @"type" : @"1"
                           };
    [[AFNetworkTool shareManager]postJSONWithUrl:Stu_Evaluate parmas:dict successData:^(id json) {
        NSArray *arr = json[@"list"];
        for (NSDictionary *dict in arr) {
            QuestionsModel * model = [QuestionsModel yy_modelWithJSON:dict];
            [weakSelf.questionArray addObject:model];
        }
        if (self.questionArray > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.title = [NSString stringWithFormat:@"评价(共%lu道题)",(unsigned long)self.questionArray.count];
                [weakSelf.tableView reloadData];
                //创建滚动视图
                [self setupScrlloView];
                //加载底部视图
                [self setupBottomView];
            });
        }else{
            [self.view addSubview:self.noDataView];
            self.title = @"评价";
            self.view.backgroundColor = [UIColor whiteColor];
        }

    } failure:^(NSError *error) {
        [self.view addSubview:self.noDataView];
        self.title = @"评价";
        self.view.backgroundColor = [UIColor whiteColor];
    }];
}
//加载底部视图
- (void)setupBottomView {
    self.topButton = [[UIButton alloc]init];
    self.topButton.frame = CGRectMake(30, self.view.bounds.size.height-60, 70, 40);
    [self.topButton setTitle:@"上一题" forState:UIControlStateNormal];
    self.topButton.backgroundColor = [UIColor orangeColor];;
    self.topButton.layer.cornerRadius = 5;
    [self.topButton addTarget:self action:@selector(topPageClick) forControlEvents:UIControlEventTouchUpInside];
    if (self.page == 0) {
        self.topButton.enabled = NO;
        self.topButton.backgroundColor = [UIColor lightGrayColor];
    }
    [self.view addSubview:self.topButton];
    
    self.nextButton = [[UIButton alloc]init];
    self.nextButton.frame = CGRectMake(self.view.bounds.size.width-100, self.view.bounds.size.height-60, 70, 40);
    [self.nextButton setTitle:@"下一题" forState:UIControlStateNormal];
    self.nextButton.backgroundColor = [UIColor orangeColor];
    self.nextButton.layer.cornerRadius = 5;
    [self.nextButton addTarget:self action:@selector(nextPageClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextButton];
}
//创建滚动视图
- (void)setupScrlloView {
    self.contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-100)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.contentScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * self.questionArray.count, 0);
    self.contentScrollView.showsHorizontalScrollIndicator = NO;
    self.contentScrollView.showsVerticalScrollIndicator = NO;
    self.contentScrollView.pagingEnabled = YES;
    self.contentScrollView.scrollEnabled = NO;
    self.contentScrollView.bounces = NO;
    self.contentScrollView.delegate = self;
    [self.view addSubview:self.contentScrollView];
    for (int i=0;i<self.questionArray.count;i++) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width*i, 0, self.view.bounds.size.width, self.view.bounds.size.height-80) style:UITableViewStyleGrouped];
        self.tableView.tag = i+1;
        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 80;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.tableView registerNib:[UINib nibWithNibName:@"XXQuestionTitleCell" bundle:nil] forCellReuseIdentifier:@"XXQuestionTitleCell"];
        [self.tableView registerNib:[UINib nibWithNibName:@"XXAnswerCell" bundle:nil] forCellReuseIdentifier:@"XXAnswerCell"];
        [self.tableView registerNib:[UINib nibWithNibName:@"XXTextCell" bundle:nil] forCellReuseIdentifier:@"XXTextCell"];
        [self.contentScrollView addSubview:self.tableView];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 5;
    }else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01;
    }else{
        return 15;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    QuestionsModel *model = self.questionArray[tableView.tag-1];
    XXQuestionTitleCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"XXQuestionTitleCell"];
    XXAnswerCell *answerCell = [tableView dequeueReusableCellWithIdentifier:@"XXAnswerCell"];
    XXTextCell *textCell = [tableView dequeueReusableCellWithIdentifier:@"XXTextCell"];
    textCell.backgroundColor = [UIColor clearColor];
    textCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if(indexPath.section == 0) {
        titleCell.cellPage = tableView.tag;
        titleCell.model = model;
        return titleCell;
    }if (indexPath.section == 1) {
        answerCell.contentLabel.text = self.answerArray[indexPath.row][@"xxnr"];
        
        return answerCell;
    }else{
        textCell.ComentText.delegate = self;
        textCell.ComentText.text = self.advise;
        return textCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section ==2) {
        return 120;
    }else{
        return tableView.rowHeight;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QuestionsModel * model = self.questionArray[tableView.tag - 1];
    if (indexPath.section == 1) {
        self.types =[NSString stringWithFormat:@"%@", self.answerArray[indexPath.row][@"id"]] ;
        self.questionID = model.questionID;
    }
    
}
-(void)textViewDidChange:(UITextView *)textView{
    self.advise = textView.text;
    QuestionsModel * model = self.questionArray[self.page];
    self.questionID = model.questionID;
}

-(void)addData{
    
    NSString *peopleid = [[NSUserDefaults standardUserDefaults] objectForKey:@"jid"];
    NSDictionary *dict = @{ @"sid" : Sid,
                            @"spass" : Spassword,
                            @"type" : @"1",
                            @"content":self.advise,
                            @"eid" : self.questionID,
                            @"star" : self.types,
                            @"peopleid" : peopleid
                            };
  //  NSLog(@">a>%@", dict);
        [[AFNetworkTool shareManager]postJSONWithUrl:Stu_PostEvaluate parmas:dict successData:^(id json) {

            
        } failure:^(NSError *error) {
    
        }];
    
}

-(void)checkData{
    
    [self addData];
    NSString *peopleid = [[NSUserDefaults standardUserDefaults] objectForKey:@"jid"];
    NSDictionary *dict = @{ @"sid" : Sid,
                            @"spass" : Spassword,
                            @"type" : @"1",
                            @"peopleid" : peopleid
                            };
    [[AFNetworkTool shareManager]postJSONWithUrl:Stu_PostEvaluate parmas:dict successData:^(id json) {
            NSArray *allnum = json[@"allnum"];
            if (allnum.count == self.questionArray.count) {
                [self popView];
            }else{
                [Utility showFail:@"还有评价未选择!"];
            }
    } failure:^(NSError *error) {
        
    }];
}
//上一题
- (void)topPageClick {
    
    if (self.page == 0) {
        self.topButton.enabled = NO;
        [self.topButton setBackgroundColor:[UIColor lightGrayColor]];
    }
    if (self.page > 0) {
        [self.submitButton removeFromSuperview];
        self.nextButton.hidden = NO;
        self.page --;
        [UIView animateWithDuration:0.3 animations:^{
            self.contentScrollView.contentOffset = CGPointMake(self.view.bounds.size.width*self.page, 0);
        }];
    }
}
- (void)setnextPageClick{
    self.page ++;
    self.topButton.enabled = YES;
    self.topButton.backgroundColor = [UIColor orangeColor];
    [UIView animateWithDuration:0.3 animations:^{
        self.contentScrollView.contentOffset = CGPointMake(self.view.bounds.size.width*self.page, 0);
    }];
    
    if(self.page+1 == self.questionArray.count) {
        self.nextButton.hidden = YES;
        self.submitButton = [[UIButton alloc]init];
        self.submitButton.frame = CGRectMake(self.view.bounds.size.width-100, self.view.bounds.size.height-60, 70, 40);
        [self.submitButton setTitle:@"提交" forState:UIControlStateNormal];
        self.submitButton.backgroundColor = [UIColor orangeColor];
        self.submitButton.layer.cornerRadius = 5;
        [self.submitButton addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.submitButton];
    }
    [self addData];
}
//下一题
- (void)nextPageClick {
    if ([self.types isEqualToString:@""]) {
        [Utility showFail:@"请选择满意度"];
    }else{
        if ([self.types isEqualToString:@"5"]) {
            if ([self.advise isEqualToString:@""]) {
                [Utility showFail:@"请填写差评原因"];
            }else{
                [self setnextPageClick];
            }
        }else{
            [self setnextPageClick];
        }
    }
    self.advise = @"";
    self.types = @"";

}
//提交答案
- (void)submitClick {
    
    if ([self.types isEqualToString:@""]) {
        [Utility showFail:@"请选择满意度"];
    }else{
        if ([self.types isEqualToString:@"5"]) {
            if ([self.advise isEqualToString:@""]) {
                [Utility showFail:@"请填写差评原因"];
            }else{
                    [self checkData];
                
            }
        }else{
               [self checkData];
            
        }
    }
    
}

-(void)popView{
    
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[CommentHisVC class]]) {
            CommentHisVC *A =(CommentHisVC *)controller;
            [self.navigationController popToViewController:A animated:YES];
        }
    }
}
#pragma mark - 懒加载

- (NSMutableArray *)questionArray {
    if(!_questionArray) {
        _questionArray = [NSMutableArray array];
    }
    return _questionArray;
}

- (NSMutableArray *)didArray {
    if(!_didArray) {
        _didArray = [NSMutableArray array];
    }
    return _didArray;
}

-(UIView *)noDataView{
    
    if (!_noDataView) {
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height+80+10, ScreenWidth, 60)];
        _noDataView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"NoData"];
        [_noDataView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_noDataView);
            make.top.mas_equalTo(50);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(100);
        }];
        
        UILabel * la = [[UILabel alloc]init];
        la.text = @"亲,暂时没有信息!";
        la.textColor = [UIColor darkGrayColor];
        la.textAlignment = NSTextAlignmentCenter;
        [_noDataView addSubview:la];
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_noDataView);
            [make.top.mas_equalTo(imageView.mas_bottom) setOffset:10];
            make.width.mas_equalTo(200);
        }];
    }
    return _noDataView;
}
@end

